package com.dayuanit.mall.bank.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dayuanit.mall.bank.domain.SinaNotifyResponse;
import com.dayuanit.mall.bank.domain.SinaOrder;
import com.dayuanit.mall.bank.dto.AjaxResultDTO;
import com.dayuanit.mall.bank.dto.SinaPayQuery;
import com.dayuanit.mall.bank.dto.SinaPayRequest;
import com.dayuanit.mall.bank.dto.SinaPayResponse;
import com.dayuanit.mall.bank.exception.MallBusException;
import com.dayuanit.mall.bank.service.SinaOrderService;

@Controller
@RequestMapping("/sina")
public class SinaGatewayController extends BankBaseController {
	
	@Autowired
	private SinaOrderService sinaOrderService;
	
	@RequestMapping("/receiveOrderLoading")
	public String receiveOrderLoading(SinaPayRequest sinaPayRequest, HttpServletRequest request) {
		log.info("商户{}，交易金额{},签名方式{}", sinaPayRequest.getMerchantAcctId(), sinaPayRequest.getOrderAmount(),sinaPayRequest.getSignType());
		
		//TODO 验证IP (可选的)
		String merchantIp = request.getRemoteAddr();
		
		//TODO 验证商户ID是否合法
		
		try {
			SinaOrder so = sinaOrderService.addOrder(sinaPayRequest);
			request.setAttribute("sinaOrder", so);
			return "sinaPay";
		} catch(MallBusException me) {
			log.error("创建订单失败{}，错误码{}", me.getMessage(), me.getErrorCode(), me);
		} catch(Exception e) {
			log.error("创建订单失败{}", e.getMessage(), e);
		}
		
		return "redirect:/error.html";
		
	}
	
	@RequestMapping("/sinaPay")
	@ResponseBody
	public AjaxResultDTO sinaPay(String pwd, int id) {
		SinaNotifyResponse snr = null;
		try {
			snr = sinaOrderService.sinaPay(id, pwd);
		} catch(MallBusException me) {
			log.error("订单支付失败{}，错误码{}", me.getMessage(), me.getErrorCode(), me);
			return AjaxResultDTO.failed(me.getMessage(), me.getErrorCode());
		} catch(Exception e) {
			log.error("订单支付失败{}", e.getMessage(), e);
			return AjaxResultDTO.failed("支付失败，请联系客服");
		}
		
		return AjaxResultDTO.success(snr);
	}
	
	@RequestMapping("/receiveQuerySharing")
	@ResponseBody
	public AjaxResultDTO receiveQuerySharing(SinaPayQuery sinaPayQuery) {
		try {
			SinaPayResponse respon = sinaOrderService.getOrder(sinaPayQuery);
			return AjaxResultDTO.success(respon);
		} catch(MallBusException me) {
			return AjaxResultDTO.failed(me.getMessage(), me.getErrorCode());
		}
	}

}
